//
//  UITextView+emoji.m
//  Emoticon
//
//  Created by 袁量 on 2017/8/14.
//  Copyright © 2017年 袁量. All rights reserved.
//

#import "UITextView+emoji.h"

@implementation UITextView (emoji)
- (void)insertEmoticon:(Emoticon *)emoticon{
    UIFont *font = [self font];
    if (emoticon.isEmpty) {
        return;
    }
    if (emoticon.isRemove) {
        [self deleteBackward];
        return;
    }
    if (emoticon.emojiCode != nil) {
        UITextRange  *textRange = [self selectedTextRange];
        [self replaceRange:textRange withText:emoticon.emojiCode];
        return;
    }
    //    普通表情
    EmoticonAttachment *attachment = [[EmoticonAttachment alloc] init];
    attachment.chs = emoticon.chs;
    attachment.bounds = CGRectMake(0, -4, self.font.lineHeight, self.font.lineHeight);
    attachment.image = [UIImage imageWithContentsOfFile:emoticon.pngPath];
    NSAttributedString *attributedString = [NSAttributedString attributedStringWithAttachment:attachment];
    NSMutableAttributedString *attributedMutableString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedMutableString replaceCharactersInRange:[self selectedRange] withAttributedString:attributedString];
    self.attributedText = attributedMutableString;
    self.font = font;
    self.selectedRange = NSMakeRange([self selectedRange].location +1, 0);
    
}
- (NSString *)getEmoticonString{
    NSMutableAttributedString *attributedMutableString = [[NSMutableAttributedString alloc] initWithAttributedString:self.attributedText];
    [attributedMutableString enumerateAttributesInRange:NSMakeRange(0, attributedMutableString.length) options:0 usingBlock:^(NSDictionary<NSString *,id> * _Nonnull attrs, NSRange range, BOOL * _Nonnull stop) {
        EmoticonAttachment *emoticonAttachment = [[EmoticonAttachment alloc] init];
        if (attrs[@"NSAttachment"] != nil) {
            emoticonAttachment = attrs[@"NSAttachment"];
            [attributedMutableString replaceCharactersInRange:range withString:emoticonAttachment.chs];
        }
    }];
    return attributedMutableString.string;
} 
@end
